package com.longlong.config.security.handler;

import com.longlong.vo.ResponseEnum;
import com.longlong.vo.ResultBody;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 没有权限访问资源
 *
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(403);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();

        writer.write(new ObjectMapper().writeValueAsString(ResultBody.fail(ResponseEnum.FORBIDDEN.getCode(),ResponseEnum.FORBIDDEN.getMessage())));
        writer.flush();
        writer.close();
    }
}
